<template>
  <div class="content1">
    <el-row :gutter="24">
      <!-- <el-col :xs="24" :sm="24" :md="6" :lg="4" :xl="4" style="border-right:1px solid #e4e4e4"> -->
      <div class="content">

        <div class="left">
          <el-form ref="form" :model="formData" label-width="0" size="mini">
            <el-row :gutter="24">
              <el-col :xs="23" :sm="23" :md="23" :lg="23" :xl="23" style="padding-top:10px">
                <el-form-item label-position="left" style="margin-bottom:5px">
                  <el-input v-model="formData.keyword" clearable placeholder="" class="search">
                    <template slot="append">
                      <el-button type="primary" size="small" @click="handleSearch">{{ $t("common.query") }}</el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="23" :sm="23" :md="23" :lg="23" :xl="23" style="padding-top:10px">
                <el-button type="primary" size="mini" @click="handleAdd()">{{ $t("common.add") }}</el-button>
                <el-button type="primary" size="mini" @click="handleEdit()">{{ $t("common.edit") }}</el-button>
                <el-button type="primary" size="mini" @click="handleDel()">{{ $t("common.remove") }}</el-button>
              </el-col>
            </el-row>
          </el-form>

          <div class="tableAuto">
            <el-table :data="tableData" :height="height" style="width:100%" stripe :header-cell-style="{background:'#EAEBEC'}"
              v-loading="tableLoading" @row-click="rowClick" ref="refTable" highlight-current-row>
              <el-table-column label="" width="50" align="center">
                <template slot-scope="scope">
                  <div>
                    <el-radio :label="scope.row.fid" v-model="radioId">&nbsp;</el-radio>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="userGroupName" width="" show-overflow-tooltip label=""></el-table-column>
            </el-table>
          </div>
          <!-- <div class="pagination-area">
                    <el-pagination
                        @current-change="handleCurrentChange"
                        :page-size="pager.pageSize"
                        :current-page="pager.pageNum"
                        layout="prev, pager, next"
                        :total="pager.total">
                    </el-pagination>
                </div> -->
        </div>
        <div class="right">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <tableContent :userList="userList" :menuList="menuList" :description="description" :screenWidth="screenWidth"></tableContent>
          </el-col>
        </div>
      </div>
    </el-row>

    <el-dialog v-dialogDrag :title="title" :visible.sync="isShowAdd" :close-on-click-modal="false"
      :width="screenWidth < 1024 ? '55%' : '35%'" :before-close="handleClose">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="85px" size="small" :hide-required-asterisk="true">
        <el-row :gutter="24">
          <el-col :xs="24">
            <el-form-item :label="$t('dialog.user_group_name')" prop="userGroupName">
              <el-input v-model="ruleForm.userGroupName" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('system.menu_name')" class="adminSelect">
              <!-- <el-select-tree :defaultProps="defaultProps" v-model="ruleForm.sysMenuVos" multiple collapse-tags clearable :data="sysMenuVosList" placeholder="xxxxxxx"></el-select-tree> -->
              <el-select-tree size="mini" :data="sysMenuVosList" expand :multiple="true" v-model="ruleForm.sysMenuVos"
                :parentSelectable="false" filterable @select="handleNameNodeClick(...arguments)" />

              <!-- <select-tree :data="sysMenuVosList" clearable checkStrictly @getValue="setTreeMenu" :obj="defaultProps" :multiple="true"
                :defaultKey="ruleForm.sysMenuVos" :count="count"></select-tree> -->

              <!-- <el-select multiple v-model="ruleForm.sysMenuVos" placeholder="" :disabled="title == '编辑用户组'">
                                <el-option v-for="item in sysMenuVosList" :key="item.fid" :label="item.menuName" :value="item.fid"></el-option>
                            </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('system.user_name')" class="adminSelect">
              <el-select multiple v-model="ruleForm.sysUserVos" placeholder="">
                <el-option v-for="item in sysUserVosList" :key="item.fid" :label="item.faccount" :value="item.fid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('common.describe')" prop="flastModifyComment">
              <el-input type="textarea" v-model="ruleForm.flastModifyComment" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleConfirm('ruleForm')"
          :loading="loading">{{ $t("common.preservation") }}</el-button>
        <el-button @click="handleClose()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>
    </el-dialog>

  </div>

</template>

<script>
import { userAdmin } from "@/api/userAdmin"
import tableContent from "./table.vue"
import selectTree from "../../../../components/selectTree.vue"
import elSelectTree from "../../../../components/elSelectTree.vue"
export default {
  components: {
    tableContent,
    selectTree,
    elSelectTree
  },
  data () {
    return {
      screenWidth: document.body.clientWidth, // 初始化屏幕宽度
      height: "calc(100vh - 275px)",
      formData: {},
      tableData: [],
      title: this.$t('dialog.user_group_add'),
      isShowAdd: false,
      ruleForm: {
        userGroupName: "",//用户组名称
        sysMenuVos: [],
        sysUserVos: [],
        flastModifyComment: ""
      },
      sysMenuVosList: [],
      sysUserVosList: [],
      rules: {
        userGroupName: [{ required: true, message: '用户组名称不能为空', trigger: 'blur' }],
        sysMenuVos: [{ required: true, message: '请选择菜单', trigger: 'change' }],
        sysUserVos: [{ required: true, message: '请选择用户', trigger: 'change' }],
      },
      loading: false,
      tableLoading: false,
      radioId: "",
      pager: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      userList: [],
      menuList: [],
      description: "",
      defaultProps: {
        children: 'children',
        label: 'menuName',
        id: 'fid'
      },
      count: 0,
      test: ""
    }
  },
  created () {
    this.getSysUserGroupList()
    this.getSysMenuList()

    this.getSysUserList()

  },
  watch: {
    screenWidth (val) {
      if (val <= 990) {
        this.height = ""
      } else {
        this.height = "calc(100vh - 275px)"
      }
    }
  },
  mounted () {
    this.updateScreenSize();
    window.addEventListener('resize', this.updateScreenSize);
  },
  beforeUnmount () {
    // 组件卸载前移除事件监听器，避免内存泄漏
    window.removeEventListener('resize', this.updateScreenSize);
  },
  methods: {
    updateScreenSize () {
      this.screenWidth = document.documentElement.clientWidth || document.body.clientWidth;
    },
    //获取用户列表
    getSysUserList () {
      const param = {
        faccount: "",
        page: 1,
        size: 99999
      }
      userAdmin.getSysUserList(param).then(res => {
        if (res.code == 200) {
          if (res.data.rows && res.data.rows.length) {
            this.sysUserVosList = res.data.rows.filter(item => {
              return item.faccount != "admin"
            })
          }

        }
      })
    },
    //获取菜单列表
    getSysMenuList () {
      const param = {
        menuName: ""
      }
      userAdmin.getSysMenuList(param).then(res => {
        if (res.code == 200) {
          // res.data.rows.forEach(item => {
          //   if (item.children.length > 0) {
          //     item.disabled = true
          //   }
          // })
          this.sysMenuVosList = res.data.rows
          this.getSysUserGroupList('init')
        }
      })
    },
    handleSearch () {
      this.pager.pageNum == 1
      this.getSysUserGroupList()
    },
    //获取用户组列表
    getSysUserGroupList (type) {
      const param = {
        userGroupName: this.formData.keyword,
        page: this.pager.pageNum,
        size: 999999
      }
      this.tableLoading = true
      userAdmin.getSysUserGroupList(param).then(res => {
        this.tableLoading = false
        console.log(res)
        if (res.code == 200) {
          this.tableData = res.data.rows
          // this.pager.total = res.data.total
          if (this.tableData.length > 0) {
            if (type == 'init') {
              this.radioId = this.tableData[0].fid
              this.rowClick(this.tableData[0])
            }


          }
          if (this.title == this.$t('dialog.user_group_edit')) {
            let row = this.tableData.find(item => item.fid == this.radioId)
            this.rowClick(row)
          }
        }
      })
    },
    handleCurrentChange (val) {
      this.pager.pageNum = val;
      this.getSysUserGroupList()
    },
    rowClick (row) {

      this.radioId = row.fid
      let sysUserVos = row.sysUserVos ? JSON.parse(JSON.stringify(row.sysUserVos)) : []
      sysUserVos.forEach(item => {
        item.fsignature = item.fsignature == 1 ? true : false
      })
      this.userList = sysUserVos
      let sysMenuVos = row.sysMenuVos ? JSON.parse(JSON.stringify(row.sysMenuVos)) : []

      // 创建一个空对象来存储菜单A中所有子菜单项的parentId及其对应的子菜单项数组
      let menuAChildMap = {};
      sysMenuVos.forEach(itemA => {
        if (itemA.parentId !== null) {
          if (!menuAChildMap[itemA.parentId]) {
            menuAChildMap[itemA.parentId] = [];
          }
          menuAChildMap[itemA.parentId].push(itemA);
        }
      });

      // 创建一个集合保存菜单A中子菜单项的parentId
      let menuAParentIds = new Set(Object.keys(menuAChildMap));
      sysMenuVos.forEach(itemA => {
        if (itemA.parentId === null) {
          menuAParentIds.add(itemA.fid);
        }
      });
      // 遍历完整的菜单数据B，过滤并构建新的菜单B结构
      let filteredMenuB = this.sysMenuVosList.reduce((acc, itemB) => {
        // 如果当前项是菜单A中的父级菜单项或本身就是菜单A中的顶级菜单项，则添加到结果集
        if (menuAParentIds.has(itemB.fid)) {
          acc.push({
            ...itemB,
            children: []
          });
        }

        // 同时查找菜单A中缺失父级但实际存在于菜单B中的子菜单项，并将其添加至相应父级菜单下
        if (menuAChildMap[itemB.fid]) {
          let parentInAcc = acc.find(parentItem => parentItem.fid === itemB.fid);
          if (parentInAcc) {
            parentInAcc.children = menuAChildMap[itemB.fid];
          }
        }

        return acc;
      }, []);


      console.log(JSON.parse(JSON.stringify(filteredMenuB)))
      this.menuList = filteredMenuB

      this.description = row.flastModifyComment
      this.$refs.refTable.setCurrentRow(row);
    },
    handleAdd () {
      this.title = this.$t('dialog.user_group_add')
      this.ruleForm = {}
      this.$set(this.ruleForm, 'sysMenuVos', [])
      this.$set(this.ruleForm, 'sysUserVos', [])
      try {
        this.$refs['ruleForm'].resetFields();
      } catch (e) {
        console.log(e)
      }
      this.count++
      this.isShowAdd = true
    },
    handleEdit () {
      if (this.radioId === '') {
        this.$message.error('请选择要修改的用户组');
        return
      }
      let sysMenuVos = []
      userAdmin.findSysUserGroup(this.radioId).then(res => {
        if (res.code == 200) {
          this.title = this.$t('dialog.user_group_edit')
          this.ruleForm = {
            userGroupName: res.data.userGroupName,
            sysMenuVos: [],
            sysUserVos: [],
            fid: res.data.fid,
            flastModifyComment: res.data.flastModifyComment
          }
          if (res.data.sysMenuVos) {
            res.data.sysMenuVos.forEach(item => {
              sysMenuVos.push(item.fid)
            })
            this.ruleForm.sysMenuVos = sysMenuVos.join(',')
          }
          let sysUserVos = []
          if (res.data.sysUserVos) {
            res.data.sysUserVos.forEach(item => {
              sysUserVos.push(item.fid)
            })
            this.sysUserVosList.forEach(item => {
              const element = sysUserVos.find(item1 => item1 == item.fid)
              if (element) {
                this.ruleForm.sysUserVos.push(element)
              }
            })
          }
          console.log(this.ruleForm)
          this.count++
          this.isShowAdd = true


        }

      })
    },
    handleDel () {
      if (this.radioId === '') {
        this.$message.error('请选择要删除的用户组');
        return
      }
      let that = this
      const el = this.tableData.find(item => item.fid == this.radioId)
      userAdmin.findSysUserGroup(this.radioId).then(res => {
        if (res.code == 200) {
          this.$customConfirm({
            content: "请确认是否删除用户组" + el.userGroupName,
            onok () {
              userAdmin.removeSysUserGroup(that.radioId).then(res => {
                if (res.code == 200) {
                  that.radioId = ""
                  that.getSysUserGroupList()
                  that.userList = []
                  that.menuList = []
                  that.$message({ duration: 1000, type: 'success', message: '删除成功!' });
                }
              })
            }
          })
        }
      })
    },
    handleConfirm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = {
            userGroupName: this.ruleForm.userGroupName,
            sysMenuVos: [],
            sysUserVos: [],
            flastModifyComment: this.ruleForm.flastModifyComment,
          }
          console.log(this.ruleForm.sysMenuVos)
          if (this.ruleForm.sysMenuVos.length > 0) {
            param.sysMenuVos = this.ruleForm.sysMenuVos.split(',').map(item => {
              return {
                fid: item
              }
            })
          } else {
            param.sysMenuVos = []
          }
          if (this.ruleForm.sysUserVos) {
            param.sysUserVos = this.ruleForm.sysUserVos.map(item => {
              return {
                fid: item
              }
            })
          } else {
            param.sysUserVos = []
          }

          if (this.title == this.$t('dialog.user_group_edit')) {
            param.fid = this.ruleForm.fid
          }
          // console.log(this.sysMenuVosList)
          // console.log(this.ruleForm.sysMenuVos.split(','))
          // console.log(this.mergeParentFidsIntoArrayB(this.sysMenuVosList,this.ruleForm.sysMenuVos.split(',')))
          // return
          this.loading = true
          userAdmin.addSysUserGroup(param, this.title).then(res => {
            this.loading = false
            if (res.code == 200) {
              this.getSysUserGroupList()
              this.isShowAdd = false
            }
          })
        }
      })
    },
    mergeParentFidsIntoArrayB (arrayA, arrayB) {
      const parentFids = [];

      arrayB.forEach(bFid => {
        for (const item of arrayA) {
          if (item.children) {
            const childNode = item.children.find(child => child.fid === bFid);
            if (childNode && !parentFids.includes(item.fid)) {
              parentFids.push(item.fid);
              break;
            }
          }
        }
      });

      // 合并arrayB和parentFids，去除重复值
      const mergedArray = [...new Set([...arrayB, ...parentFids])];

      return mergedArray;
    },
    handleClose () {
      this.isShowAdd = false
      this.$refs['ruleForm'].resetFields();
    },
    treeCheck (data, list) {
      console.log(data, list)
    },
    setTreeMenu (key, data) {//获取子组件值
      this.ruleForm.sysMenuVos = key
      if (this.ruleForm.sysMenuVos.length) {
        this.$refs['ruleForm'].clearValidate("sysMenuVos");
      }
      // console.log(key)
      // console.log(data)
    },
    handleNameNodeClick (index, data, node) {
      //点击与树节点相关数据都在index data node,按照需求获取即可
      console.log(data)
      console.log(node)
    },
  }
}
</script>
<style scoped>
.search >>> .el-input-group__append,
.search >>> .el-input-group__prepend {
  background: #00a09d;
  color: #fff;
  border: 1px solid #00a09d;
}
.adminSelect >>> .el-select {
  width: 100%;
}
.tableAuto >>> .el-table__row {
  background: none !important;
}
.tableAuto >>> .el-table--striped .el-table__body tr.el-table__row--striped td {
  background: none;
}
.tableAuto >>> .el-table__row td {
  padding: 8px 0;
}
.tableAuto >>> .el-table thead {
  display: none;
}
.pagination-area {
  padding-top: 0px;
}

.content {
  display: flex;
  height: 100%;
  padding-top: 10px;
  clear: both;
}
.content .left {
  width: 210px;
  border-right: 1px solid #e4e4e4;
  height: 100%;
}
.content .right {
  flex: 1;
  padding-left: 15px;
}
</style>